<script lang="ts" setup>
import { nextTick, ref } from 'vue'

const tags = ref(['效果好', '价格实惠'])
const inputRef = ref<HTMLInputElement>()
const showInput = ref(false)
const inputVal = ref('')

const handleEdit = () => {
  showInput.value = true

  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus()
    }
  })
}

const handleAdd = () => {
  if (inputVal.value) {
    if (!tags.value.includes(inputVal.value)) {
      tags.value.push(inputVal.value)
    }
    inputVal.value = ''
  }
  showInput.value = false
}

const handleRemove = (key: string) => {
  tags.value = tags.value.filter((tag) => tag !== key)
}
</script>

<template>
  <div class="flex gap-4 flex-wrap">
    <a-tag v-for="(tag, index) of tags" :key="tag" closable @close="handleRemove(tag)">
      {{ tag }}
    </a-tag>

    <a-input
      v-if="showInput"
      ref="inputRef"
      :style="{ width: '90px' }"
      size="mini"
      v-model.trim="inputVal"
      @keyup.enter="handleAdd"
      @blur="handleAdd"
    />
    <a-tag
      v-else
      :style="{
        width: '90px',
        backgroundColor: 'var(--color-fill-2)',
        border: '1px dashed var(--color-fill-3)',
        cursor: 'pointer'
      }"
      @click="handleEdit"
    >
      <template #icon>
        <icon-plus />
      </template>
      Add Tag
    </a-tag>
  </div>
</template>
